import 'package:flutter/material.dart';
import '../../util/_base_export.dart';
import '../../util/_view_export.dart';
import './page_controller/shop_scroll_controller.dart';
import './page_controller/shop_scroll_coordinator.dart';
import '../../blocs/menu.dart';
import '../../blocs/cart.dart';

class SubMenuPage extends StatefulWidget {
  late ShopScrollCoordinator shopCoordinator;
  late TabController tabController;

  List? cate3_list;

  SubMenuPage(
      {
        required this.shopCoordinator,
        required this.tabController,
        this.cate3_list,
        Key? key
      }): super(key: key);

  @override
  _SubMenuPageState createState() => _SubMenuPageState();
}

class _SubMenuPageState extends State<SubMenuPage> {
  ShopScrollCoordinator? _shopCoordinator;
  ShopScrollController? _listScrollController1;
  ShopScrollController? _listScrollController2;
  int selectedindex = 0;
  List _prod_list = [];

  @override
  void initState() {
    super.initState();
    _shopCoordinator = widget.shopCoordinator;
    _listScrollController1 = _shopCoordinator?.newChildScrollController();
    _listScrollController2 = _shopCoordinator?.newChildScrollController();
    widget.tabController.addListener(_handleTabSelection);
    filterProduct(widget.cate3_list?[0]['cate3_id']);
  }

  _handleTabSelection() async {
    var result = await Provider.of<MenuBloc>(context, listen: false)
        .getCate3List(Provider.of<MenuBloc>(context, listen: false)
            .sub_category_list[widget.tabController.index]['cate2_id']);
    if (result['ev_error'] == 0) {
      filterProduct(widget.cate3_list?[0]['cate3_id']);
    }
  }

  filterProduct(int cate_id) {
    if(mounted){
      setState(() {
        _prod_list = [];
      });
    }
    if (Provider.of<MenuBloc>(context, listen: false).prod_list.length != 0) {
      Provider.of<MenuBloc>(context, listen: false)
          .prod_list
          .forEach((element) {
        if (element['cate3_id'] == cate_id) {
          setState(() {
            _prod_list = element['prods'];
          });
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        Expanded(
            flex: 90,
            child: Container(
              color: Color(0xffF4F4F4),
              child: ListView.builder(
                padding: EdgeInsets.all(0),
                physics: AlwaysScrollableScrollPhysics(),
                controller: _listScrollController1,
                itemCount: widget.cate3_list?.length ?? 0,
                itemBuilder: (BuildContext context, int index) {
                  var _item = widget.cate3_list?[index];
                  return Container(
                    height: 55.h,
                    child: Material(
                        color: selectedindex == index
                            ? Colors.white
                            : Color(0xffF4F4F4),
                        child: GestureDetector(
                          onTap: () {
                            setState(() {
                              selectedindex = index;
                            });
                            filterProduct(_item['cate3_id']);
                          },
                          child: Center(
                              child: Text(_item['cate3_name'],
                                  style: TextStyle(
                                    color: selectedindex == index
                                        ? Color(0xffFF9F05)
                                        : Color(0xff606060),
                                  ))),
                        )),
                  );
                },
              ),
            )),
        Expanded(
          flex: 285,
          child: ListView.builder(
            padding: EdgeInsets.all(0),
            physics: AlwaysScrollableScrollPhysics(),
            controller: _listScrollController2,
            itemCount: _prod_list.length,
            itemBuilder: (BuildContext context, int index) {
              var _item = _prod_list[index];
              return generateItem(context, _item, index);
            },
          ),
        ),
      ],
    );
  }

  static Widget generateItem(BuildContext context, Map item, int index) {
    late Offset temp;
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTap: () {
          App.router.navigateTo(
              context, AppRoutes.productDetail + '?prod_id=${item['sku_id']}');
        },
        child: Container(
            color: Colors.white,
            width: 285.w,
            height: 167.h,
            padding: EdgeInsets.only(left: 14.w, right: 12.w, top: 18.h),
            child: Column(children: [
              Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisAlignment: MainAxisAlignment.start,
                children: <Widget>[
                  Container(
                    width: 70.w,
                    height: 70.h,
                    margin: EdgeInsets.only(
                      right: 12.w,
                    ),
                    child: CachedNetworkImage(
                      imageUrl: item['image_url'],
                      fit: BoxFit.cover,
                    ),
                  ),
                  Container(
                    height: 135.h,
                    padding: EdgeInsets.only(
                      left: 12.w,
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: <Widget>[
                        Container(
                            height: 106.h,
                            child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisAlignment: MainAxisAlignment.start,
                                children: [
                                  Container(
                                    width: 165.w,
                                    height: 33.h,
                                    child: Text(
                                      item['sku_name'],
                                      softWrap: true,
                                      maxLines: 2,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        color: AppColor.nameProduct,
                                        fontWeight: FontWeight.w500,
                                        fontSize: 12.sp,
                                      ),
                                    ),
                                  ),
                                  SizedBox(height: 4.h),
                                  Container(
                                    width: 165.w,
                                    height: 14.h,
                                    child: Text(
                                      item['sku_desc'],
                                      softWrap: true,
                                      maxLines: 1,
                                      overflow: TextOverflow.ellipsis,
                                      style: TextStyle(
                                        color: AppColor.descProduct,
                                        fontWeight: FontWeight.normal,
                                        fontSize: 10.sp,
                                      ),
                                    ),
                                  ),
                                  SizedBox(height: 4.h),
                                  Container(
                                    width: 165.w,
                                    height: 17.h,
                                    child: Text(
                                      '\$' +
                                          item['sku_price'] +
                                          '/' +
                                          item['unit_desc'],
                                      softWrap: true,
                                      maxLines: 1,
                                      style: TextStyle(
                                        color: Color(0xffFF9F05),
                                        fontWeight: FontWeight.normal,
                                        fontSize: 12.sp,
                                      ),
                                    ),
                                  ),
                                  SizedBox(height: 4.h),
                                  item['outstock_info'] == 1
                                      ? Container(
                                          width: 80.w,
                                          padding: EdgeInsets.symmetric(
                                              horizontal: 5.w),
                                          height: 16.h,
                                          decoration: BoxDecoration(
                                            color: Color(0xffFDE3E3),
                                            borderRadius:
                                                BorderRadius.circular(2),
                                          ),
                                          child: Center(
                                              child: Text('库存不足',
                                                  style: TextStyle(
                                                    color: Color(0xffFF3434),
                                                    fontSize: 10.sp,
                                                  ))))
                                      : Container(),
                                ])),
                        Row(children: [
                          Container(width: 62.w),
                          Column(children: [
                            Container(
                              width: 80.w,
                              height: 28.h,
                              child: Consumer<CartBloc>(
                                builder: (context, _cart, child) => Builder(
                                  builder: (context) {
                                    return Row(
                                      mainAxisAlignment: MainAxisAlignment.end,
                                      children: <Widget>[
                                        GestureDetector(
                                          onTap: () {
                                            _cart.reduceItem(item['sku_id']);
                                          },
                                          child: Icon(
                                            // MaterialCommunityIcons.minus_circle_outline,
                                            LineIcons.minusCircle,
                                            color: AppColor.nameProduct,
                                            size: 22,
                                          ),
                                        ),
                                        Container(
                                          padding: EdgeInsets.symmetric(
                                              horizontal: 14.w),
                                          alignment: Alignment.center,
                                          child: Text(
                                            _cart
                                                .itemAmount(item['sku_id'])
                                                .toString(),
                                            style: TextStyle(
                                              color: AppColor.nameProduct,
                                              fontWeight: FontWeight.normal,
                                              fontSize: 20.sp,
                                            ),
                                          ),
                                        ),
                                        GestureDetector(
                                          onPanDown: (details) {
                                            temp = new Offset(
                                                details.globalPosition.dx,
                                                details.globalPosition.dy);
                                          },
                                          onTap: () {
                                            late Function callback;
                                            // setState(() {
                                            _cart.addItem(item);
                                            OverlayEntry entry =
                                                OverlayEntry(builder: (ctx) {
                                              return ParabolaAnimateWidget(
                                                AppSession.homeRoot,
                                                temp,
                                                AppSession.homeCart,
                                                Icon(
                                                  Icons.add_circle,
                                                  color: Colors.redAccent,
                                                ),
                                                callback,
                                                duration: 800,
                                              );
                                            });

                                            callback = (status) {
                                              if (status ==
                                                  AnimationStatus.completed) {
                                                entry.remove();
                                              }
                                            };
                                            Overlay.of(AppSession.homeRoot.currentContext!)!.insert(entry);
                                          },
                                          child: Icon(
                                            // MaterialCommunityIcons.plus_circle,
                                            LineIcons.plusCircle,
                                            color: AppColor.nameProduct,
                                            size: 22,
                                          ),
                                        ),
                                      ],
                                    );
                                  },
                                ),
                              ),
                            ),
                          ])
                        ])
                      ],
                    ),
                  ),
                ],
              ),
              SizedBox(height: 10.5.h),
              Divider(
                color: Color(0xffcAcAcA),
                height: 1.0,
                indent: 0.0,
                endIndent: 0.0,
              ),
            ])));
  }

  @override
  void dispose() {
    _listScrollController1?.dispose();
    _listScrollController2?.dispose();
    _listScrollController1 = _listScrollController2 = null;
    super.dispose();
  }
}
